//
//  Synchronized subscriber
//

package main

import (
	"fmt"
	"os"
	"zmq"
)

func zmq_main() os.Error {
	context, err := zmq.Init(1)
	if err != nil {
		return err
	}
	defer context.Close()

	subscriber, err := context.Socket(zmq.SUB)
	if err != nil {
		return err
	}
	defer subscriber.Close()
	err = subscriber.Connect("tcp://localhost:5561")
	if err != nil {
		return err
	}
	err = subscriber.SetOptionByte(zmq.SUBSCRIBE, nil)
	if err != nil {
		return err
	}

	zmq.Sleep(1)

	syncclient, err := context.Socket(zmq.REQ)
	if err != nil {
		return err
	}
	defer syncclient.Close()

	err = syncclient.Connect("tcp://localhost:5562")
	if err != nil {
		return err
	}
	err = syncclient.Send(nil, 0)
	if err != nil {
		return err
	}
	_, err = syncclient.Recv(0)
	if err != nil {
		return err
	}

	update_nbr := 0
	for {
		s, err := subscriber.Recv(0)
		if err != nil {
			return err
		}
		if string(s) == "END" {
			break
		}
		update_nbr++
	}
	fmt.Printf("Received %d update\n", update_nbr)
	return nil
}

var errch = make(chan os.Error)

func main() {
	fmt.Println("Synchronized subscriber")
	exit := make(chan bool)
	go func() {
		for {
			err := <-errch
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}
		}
	}()
	go func() {
		err := zmq_main()
		if err != nil {
			errch <- err
		} else {	
			exit <- true
		}
	}()
	<-exit
}
